package sms

import (
	"encoding/json"
	"errors"
	openapi "github.com/alibabacloud-go/darabonba-openapi/client"
	dysm "github.com/alibabacloud-go/dysmsapi-20170525/v2/client"
	"github.com/go-emix/utils"
	"service/common/aliyun"
)

var Client *dysm.Client

func init() {
	id := aliyun.AccessKeyId
	secret := aliyun.AccessKeySecret
	config := &openapi.Config{
		AccessKeyId:     &id,
		AccessKeySecret: &secret,
	}
	ed := "dysmsapi.aliyuncs.com"
	config.Endpoint = &ed
	var err error
	Client, err = dysm.NewClient(config)
	utils.PanicError(err)
}

type Template struct {
	// 短信模板id
	Code string
	// 短信签名名称
	SignName string
	// 模板参数
	Param map[string]interface{}
}

func Send(phone string, tmpl Template) error {
	req := &dysm.SendSmsRequest{}
	req.PhoneNumbers = &phone
	req.SignName = &tmpl.SignName
	req.TemplateCode = &tmpl.Code
	marshal, err := json.Marshal(&tmpl.Param)
	if err != nil {
		return err
	}
	ps := string(marshal)
	req.TemplateParam = &ps
	resp, err := Client.SendSms(req)
	if err != nil {
		return err
	}
	code := *resp.Body.Code
	if code != "OK" {
		return errors.New(code)
	}
	return nil
}
